<template>
  <view class="table-view">
    <template v-for="(ta, ti) of tables">
      <view :style="{'width': fixedWidth[ta.type] + 'px'}" :class="ta.ref" :key="ti">
        <uni-table
          :ref="ta.ref"
          :loading="loading"
          border
          stripe
          emptyText="暂无更多数据">
          <thead>
            <uni-tr>
            <template v-for="(item, index) of headList" >
              <uni-th :width="item.width || '150'" align="center" :key="index" v-if="item.select && item.select == 'selection'">
                <uni-view class="table-checkbox" @click='selectionChangeAll(item.checked)'>
                  <uni-view class="checkbox-border" :class="item.checked ? 'is-checked' : ''">
                    <uni-view class="checkbox-icon"></uni-view>
                  </uni-view>
                </uni-view>
              </uni-th>
              <uni-th :width="item.width || '150'" align="center" :key="index" v-else-if="!item.select && item.select == 'radio'">
                <uni-view></uni-view>
              </uni-th>
              <uni-th :width="item.width || '150'" align="center" :key="index" v-else>{{item.title}}</uni-th>
            </template>
          </uni-tr>
          </thead>
          <tbody>
          <uni-tr v-for="(item, index) in tableList" :key="index" 
          :class="{'is-hover' : item.isHover}" @mouseover.native="hover(index, 'over')" @mouseout.native="hover(index, 'out')">
            <template v-for="(h, i) of headList" >
              <uni-td align="center" :key="`${index}-${i}`" v-if="h.select && h.select == 'selection'">
                <uni-view class="table-checkbox" @click='selectionChange(index)'>
                  <uni-view class="checkbox-border" :class="item.checked ? 'is-checked' : ''">
                    <uni-view class="checkbox-icon"></uni-view>
                  </uni-view>
                </uni-view>
              </uni-td>
              <uni-td :key="`${index}-${i}`" v-else-if="h.select && h.select == 'radio'">
                <uni-view class="table-checkbox" @click='radioChange(index, item.checked)'>
                  <uni-view class="checkbox-border radio-border" :class="item.checked ? 'is-checked' : ''">
                    <uni-view class="checkbox-icon"></uni-view>
                  </uni-view>
                </uni-view>
              </uni-td>
              <uni-td align="center" :key="`${index}-${i}`" v-else-if="h.format" v-html="h.format(item, index)"></uni-td>
              <uni-td align="center" :key="`${index}-${i}`" v-else-if="h.isSlot">
                <slot :data="item" :field="h.field"></slot>
              </uni-td>
              <uni-td align="center" :key="`${index}-${i}`" v-else>{{item[h.field]}}</uni-td>
            </template>
          </uni-tr>
          </tbody>
        </uni-table>
      </view>
    </template>
  </view>
</template>
<script>
export default {
	name:'pzk-uni-table',
  props: {
    //表头数据
    headData: {
      type: Array,
      default () {
        return []
      }
    },
    //表格渲染数据
    tableData: {
      type: Array,
      default () {
        return []
      }
    },
    //左边固定列数
    fixedLeft: {
      type: Number,
      default: 0,
    },
    //右边固定列数
    fixedRight: {
      type: Number,
      default: 0,
    },
    //是否固定表头
    // fixedHead: {
    //   type: Boolean,
    //   default: false,
    // },
    //表格类型，type为selection时多选，为radio时单选
    type: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      loading: false,
      selectArr: [], //点击过的列表数组，存储起来，以获取当前点击的是那个
      tableList: [],
      headList: [],
      //固定的左边数据对象
      fixedWidth: {
        left: 0,
        right: 0
      },
      radioIndex: -1, //当前选中的单选框数据下标
      checkAll: false,
    };
  },
  created() {
    this.init()
  },
  computed: {
    //需要渲染的表格数量，左右两边固定是创建两个表格
    tables() {
       let list = [{ref: 'table'}];
      if (this.fixedLeft) list.push({ref: 'leftTable', type: 'left'});
      if (this.fixedRight) list.push({ref: 'rightTable', type: 'right'});
      return list
    }
  },
  watch: {
    tableData: {
      immediate: true,
      deep: true,
      handler(newVal, oldVal) {
        let list = newVal
        if (this.type) {
          list = list.map((v)=>{
            return {checked:false, isHover: false, ...v}
          })
        }
        let checkArr = list.filter((v)=>v.checked)
        //如果为单选，并且多个数据的状态为选中，只保留最后一个数据的状态
        if (this.type == 'radio' && checkArr.length > 1) {
          for (let i = 0; i < checkArr.length-1; i++) {
            checkArr[i].checked = false
          }
          this.radioIndex = list.findIndex((v)=>v.checked)
        }
        //如果是多选，所有数据状态为选中，则表头的全选状态为选中
        //表头数据可能拿不到，先存储变量，在生成表头时处理
        if (this.type == 'selection' && checkArr.length == list.length) {
          if (this.headList[0]) {
            this.headList[0].checked = true
          }
          else { 
            this.checkAll = true
          }
        }
        this.tableList = list
      }
    }
  },
  methods: {
    //表格初始化，根据类型判断是否需要多选单选选项
    init() {
			console.log('int-table 更新测试');
      let list = this.headData
      if (this.type && !list[0].select) {
        list.unshift({checked: this.checkAll || false, select: this.type, width: '50'})
      }
      this.headList = list
      this.setFixedLeft()
      this.setFixedRight()
    },
    //根据表格单元格宽度获取左边边固定宽度
    setFixedLeft() {
      if (this.fixedLeft == 0) {
        return
      }
      let head = this.headList.slice(0, this.fixedLeft);
      this.fixedWidth.left = head.reduce((pre, cur)=>{
        return Number(pre.width || pre) + Number(cur.width || 150)
      });
    },
    //根据表格单元格宽度获取右边固定宽度
    setFixedRight() {
      if (this.fixedRight == 0) {
        return
      }
      let head = this.headList.slice(-this.fixedRight);
      this.fixedWidth.right = head.reduce((pre, cur)=>{
        return Number(pre.width || pre) + Number(cur.width || 150)
      });
    },
    // 多选框改变事件
    selectionChange(index, checked) {
      let data = this.tableList[index];
      data.checked = checked == undefined ? !data.checked : checked;
      let select = []
      this.tableList.forEach((v, i) => {
        if (v.checked) select.push(i)
      });
      if (!data.checked) {
        this.headList[0].checked = false
      }
      else if (select.length == this.tableList.length) {
        this.headList[0].checked = true
      }
      // this.$emit('selectionChange', {index: index, select: select, data: data, checked: data.checked,})
    },

    //多选框全选事件
    selectionChangeAll(checked) {
      let select = []
      this.tableList.forEach((v, i) => {
        v.checked = !checked
        if (v.checked) select.push(i)
      });
      let data = this.headList.find((v)=>v.select)
      data.checked = !checked;
      // this.$emit('selectionChange', {index: -1, select: select, checked: data.checked, data: data})
    },
    
    //单选框选择事件
    radioChange(index, checked) {
      let data = this.tableList[index];
      if (checked && data.checked == checked) { //单选按钮选中状态重复点击不处理
        return
      }
      //把之前选择的数据状态去除
      if (this.radioIndex != -1) {
        this.tableList[this.radioIndex].checked = false
      }
      data.checked = true
      this.radioIndex = index
      // this.$emit('radioChange', {index: index, checked: data.checked, data: data})
    },

    hover(index, type) {
      let data = this.tableList[index];
      if (type == 'over' && data.isHover) {
        return
      }
      else if (type == 'over') {
        data.isHover = true
      }
      else {
        data.isHover = false
      }
    }
  }
};
</script>

<style lang="less" scoped>
.table-view {
  position: relative;
  // overflow-y: scroll;
  // .table,.leftTable {
  //   height: fit-content;
  //   width: fit-content;
  // }
  // .fixedHead {
  //   overflow-y: hidden;
  //   /deep/ table {
  //     min-width: 100% !important;
  //     overflow-x: scroll;
  //   }
  //   /deep/ tbody {
  //     overflow-y: scroll;
  //   }
  //   /deep/ tbody,tr{
  //     width: 100%;
  //   }
  //   /deep/ th,td {
  //     min-height: 40px;
  //   }
  //   /deep/ thead,tbody,tr,th,td {
  //     display: inline-block;
  //   }
  // }
  .table {
    // height: 100%;
    /deep/ .uni-table-scroll {
      height: 100%;
    }
  }
  .leftTable, .rightTable {
    position: absolute;
    min-height: calc(100% - 12px);
    overflow: hidden;
    top: 0;
    /deep/ .uni-table-scroll {
      overflow: hidden;
      width: auto;
    }
  }
  .leftTable {
    left: 0;
    /deep/ .uni-table-scroll {
      left: 0;
    }
  }
  .rightTable {
    right: 0;
    /deep/ .uni-table-scroll {
      right: 0;
    }
  }
  /deep/ .uni-table-scroll {
    // height: 200px;
  }
  /deep/ .uni-table{
    tr{
      td:first-child,th:first-child{
        border-left: 1px solid #ebeef5 !important;
      }
      .table-checkbox {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        position: relative;
        margin: 5px 0;
        cursor: pointer;
        .checkbox-border.is-checked {
          border-color: #409EFF;
          background-color: #409EFF;
          .checkbox-icon{
            opacity: 1;
          }
        }
        .checkbox-border {
            flex-shrink: 0;
            box-sizing: border-box;
            position: relative;
            width: 16px;
            height: 16px;
            border: 1px solid #DCDFE6;
            border-radius: 2px;
            background-color: #fff;
            .checkbox-icon {
              position: absolute;
              top: 2px;
              left: 5px;
              height: 7px;
              width: 3px;
              border: 1px solid #fff;
              border-left: 0;
              border-top: 0;
              opacity: 0;
              transform-origin: center;
              transform: rotate(45deg);
              box-sizing: content-box;
          }
        }
        .radio-border {
          border-radius: 50%;
        }
      }
    }
    .is-hover {
      background-color: #f5f7fa;
    }
    .uni-table-tr:hover {
      background-color: #f5f7fa;
    }
    tbody {
      // max-height: 300px;
      // overflow-y: scroll;
    }
  }
  
}
</style>